import { useI18n } from "@/hooks/web/useI18n";
import { isBoolean } from "@/utils/is";
import { computed, ComputedRef, ref, unref, watch } from "vue";
import { PAGE_SIZE, PAGE_SIZE_OPTIONS } from "../const";
import { PaginationProps } from "../types/pagination";
import { BasicTableProps } from "../types/table";

export function usePagination(refProps: ComputedRef<BasicTableProps>) {
  const { t } = useI18n();

  const configRef = ref<PaginationProps>();
  const show = ref(true);

  watch(
    () => unref(refProps).pagination,
    (pagination) => {
      if (!isBoolean(pagination) && pagination) {
        configRef.value = {
          ...unref(configRef),
          ...(pagination ?? {}),
        };
      }
    }
  );

  const getPaginationInfo = computed((): PaginationProps | boolean => {
    const { pagination } = unref(refProps);

    if (!unref(show) || (isBoolean(pagination) && !pagination)) {
      return false;
    }
    return {
      currentPage: 1,
      pageSize: PAGE_SIZE,
      total: 0,
      pagerCount: 11,
      small: true,
      disabled: false,
      style: {
        display: "flex",
        justifyContent: "flex-end",
        position: 'absolute',
        right: '100px',
        bottom: '40px',
      },
      customClass: "",
      hideOnSinglePage: false,
      layout: "total, sizes, prev, pager, next, jumper",
      defaultPageSize: PAGE_SIZE,
      showTotal: (total) => t("component.table.total", { total }),
      pageSizes: PAGE_SIZE_OPTIONS,
      ...(isBoolean(pagination) ? {} : pagination),
      ...unref(configRef),
    };
  });

  function setPagination(info: Partial<PaginationProps>) {
    console.log(info);
    const paginationInfo = unref(getPaginationInfo);
    configRef.value = {
      ...(!isBoolean(paginationInfo) ? paginationInfo : {}),
      ...info,
    };
  }

  function getPagination() {
    return unref(getPaginationInfo);
  }

  function getShowPagination() {
    return unref(show);
  }

  async function setShowPagination(flag: boolean) {
    show.value = flag;
  }

  return {
    getPagination,
    getPaginationInfo,
    setShowPagination,
    getShowPagination,
    setPagination,
  };
}
